<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class  Hot extends CI_Controller
{	
	
	const SINA          = 'sina';
	const YUNYUN        = 'yunyun';
	const NETEASE       = 'netease';
	const SOHU          = 'sohu';
	const TENCENT       = 'tencent';
	const PLATFORM      = 'platform';
	const ADMIN         = 'soften';
	const ERROR_TAB     = 'error';
	const LOG_LEVEL_ERROR = 'error';
	const LOG_LEVEL_WARING = 'waring';
	const LOG_LEVEL_NOTICE = 'notice';
	public $_log_dir    = 'keyword';
	public $_result_dir = 'result';
	public $_return_data;
	
    public function __construct(){
        parent::__construct();
        $this->load->helper('MY_auth_verification');
        $this->load->library('error_code_library');
        $this->load->library('crawl_abstract');
        //$this->load->database();
        $this->_return_data = $this->config->item('return_data');
    }
    
    public function index(){
    	//$this->get_hot();
		$this->crawl();          //在本机测试时 将上面一行注释掉 打开下面一行 以跳过权限验证
    }
    
    public function get_hot() {
    	$auth_verification_result = authentication($this, $this->input->post());
    	if(is_array($auth_verification_result) && array_key_exists(self::ERROR_TAB, $auth_verification_result)) {
    		echo json_encode($auth_verification_result);
    		exit;
    	} else {
    		$this->crawl();
    	}
    }
    
    public function crawl() {
    	
    	//这里执行抓取程序并返回结果
    	$this->load->library('crawl_keyword_library');
    	$this->load->library('Crawl_sina_hot_from_html_library');
    	
    	$result = $this->crawl_sina_hot_from_html_library->crawl(FALSE);

    	
    	if( is_null($result) || array_key_exists(self::ERROR_TAB, $result) == FALSE) {
			if(array_key_exists('data', $result)) {
				$result_string = json_encode($this->_return_data);
			} else {
				$this->_return_data['data'] = $result;
				$result_string = json_encode($this->crawl_keyword_library->return_utf8_code($this->_return_data));
   			}

			log_message(self::LOG_LEVEL_NOTICE, 'Return Result Crawl String: '.$result_string, FALSE, $this->_result_dir);

			echo $result_string;
		} else {
			$this->_return_data['error'] = $result;
			log_message(self::LOG_LEVEL_ERROR, 'Crawl Error: '.json_encode($this->crawl_keyword_library->return_utf8_code($this->_return_data)), FALSE, $this->_log_dir);
			echo json_encode($this->_return_data);
		}
    }

    public function test()
    {
    	// 这里是模拟一次请求　也就是测试index方法是否正确
    	$post_data=$this->input->post();
    	header('Content-Type:text/html;charset=utf-8');            
    		
    	$post_data['cat']=$this->input->post('cat')!==FALSE?$this->input->post('cat'):'default' ;
    	
    	if(empty($post_data['cat']))
    		$post_data['cat']='default' ;
    	$post_data['dateType']=$this->input->post('dateType') ;
    	$post_data['platform'] = "sina";
    	$post_data['page']=$this->input->post('page')!==FALSE?$this->input->post('page'):1 ;
    	$post_data['token'] = "9f7ffa5b38e13b1843eeffcc3ba06565";
    	
    	$this->load->helper('url'); 	
    	$this->load->library('table');
    	
    	$url=site_url('hot/index') ; 	
    	$ch=curl_init($url);
    	curl_setopt($ch,CURLOPT_POST,1) ;
    	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true) ;
    	curl_setopt($ch, CURLOPT_HEADER, 0);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    	
    	$result =curl_exec($ch);   	
    	
    	if ($result === FALSE) {
    		echo "CURL Error In Test Connect API: " . curl_error($ch). " TO ".$url;
    	}
    	
		$result = json_decode($result, TRUE) ;
		
		if(array_key_exists(self::ERROR_TAB, $result) && !empty($result[self::ERROR_TAB])) {
			echo "<pre>";print_r($result);echo "</pre>";exit;
		}else{
			$result = $result['data'];
		}
		
 		$wbfield = array(
            '微博ID', '微博信息内容', '微博创建时间', '微博来源', '转', '评', '好', '转载的微博ID', '转载的微博用户ID', '转载的微博用户名', '详情URL',
            '缩略图片地址', '中等尺寸图片地址', '原始图片地址', '增加时间', '渠道ID抓取渠道', '用户ID', '用户空间URL', '昵称', '描述', '头像', '粉丝数', '关注数', '是否加V'
        );
    	
    	echo '<head><meta charset="utf-8"><title>'.'热点微博抓取'.'</title><style>*{font-size:12px}</style></head>';
    	
    	echo count($result).'条记录';
    	
    	$tmpl = array ( 'table_open'  => '<table border="1" cellpadding="0" cellspacing="0" class="mytable">' );
    	
    	$this->table->set_template($tmpl);
    	$this->table->set_heading($wbfield);
    	
    	
    	
    	foreach($result as $row) 
    	{
    		  		$data = array();
                    $data[] = $row['_id'];
                    $data[] = $row['text'];
                    $data[] = $row['ctime'];
                    $data[] = $row['source'];
                    $data[] = $row['reposts_count'];
                    $data[] = $row['comments_count'];
                    $data[] = $row['attitudes_count'];
                    $data[] = $row['retweeted_id'];
                    $data[] = $row['retweeted_uid'];
                    $data[] = $row['retweeted_name'];
                    $data[] = empty($row['url'])? '': "<a href='{$row['url']}' target='_blank'>{$row['url']}</a>";
                    $data[] = $row['thumbnail_pic'];
                    $data[] = $row['bmiddle_pic'];
                    $data[] = $row['original_pic'];
                    $data[] = $row['addtime'];
                    $data[] = $row['source_myid'];
                    $data[] = $row['user']['id'];
                    $data[] = empty($row['user']['profile_url'])? '': "<a href='{$row['user']['profile_url']}' target='_blank'>{$row['user']['profile_url']}</a>";
                    $data[] = $row['user']['name'];
                    $data[] = $row['user']['description'];
                    $data[] = $row['user']['header_url'];
                    $data[] = $row['user']['followers_count'];
                    $data[] = $row['user']['friends_count'];
                    $data[] = $row['user']['verified'];
                    $this->table->add_row($data);
 
    	}  
    	
    	echo $this->table->generate();
    	   
    }  
    
    public  function test1()
    {
    	$str='http://weibo.com/3267993567/Cvvu4rEPy' ;
    	$p1='/http:\/\/weibo.com\/(.*?)\/(.*)/' ;
    	preg_match($p1,$str,$m);
    	var_dump($m) ;
    }
    
   
}
